<template>
  <div class="payroll-wrap">
    <div class="payroll-box">
      <div class="title">企业名称:</div>
      <div class="name">{{name}}</div>
    </div>
    <div class="payroll-box">
      <div class="title">您的岗位:</div>
      <popup-picker :data="postList" v-model="post" placeholder="请选择理想岗位" ref="postPicker"
                    class="name work"></popup-picker>
      <div class="back-box"><img src="./back.png" class="back" onclick="return false"/></div>
    </div>
    <div class="payroll-box">
      <div class="title">薪资月份:</div>
      <datetime format="YYYY-MM" v-model="month" class="name work"
                placeholder="请选择薪资月份" :end-date="date" @on-change="selectMonth"></datetime>
      <div class="back-box"><img src="./back.png" class="back" onclick="return false"/></div>
    </div>
    <div class="payroll-box">
      <div class="title">应发工资:</div>
      <div class="name">
        <input type="text" class="money" placeholder="请输入应发工资" v-model="money1" @blur="inputBlur"/>
      </div>
    </div>
    <div class="payroll-box">
      <div class="title">实发工资:</div>
      <div class="name">
        <input type="text" class="money" placeholder="请输入实发工资" v-model="money2" @blur="inputBlur"/>
      </div>
    </div>

    <div class="pic-box">
      <span class="pic-title">工资单上传：</span>
      <div class="pay-picture">
        <div class="pay-box" v-show="!payroll">
          <div class="roll-box"><img src="./roll.png" class="roll" onclick="return false"/></div>
        </div>
        <img :src="payroll" class="payroll" v-show="payroll" onclick="return false"/>
        <input type="file" class="photo" @change="changeImage($event)"
               accept="image/*"/>
      </div>
    </div>


    <div class="btn" @click="payRoll" v-show="hideBtn">提交</div>
  </div>
</template>

<script>
  import {convertBase64ToBlob, getBase64, formatDate} from "../../common/js/util"
  import * as qiniu from 'qiniu-js'
  import {baseUrl} from "../../common/js/env"
  import {PopupPicker, Picker, Datetime} from 'vux'

  export default {
    data() {
      return {
        id: "",
        name: "",
        month: "",
        post: [],
        postList: [],
        money1: "",
        money2: "",
        payroll: "",
        userSign: "",
        date: "",
        docmHeight: document.documentElement.clientHeight,//默认屏幕高度
        showHeight: document.documentElement.clientHeight,//实时屏幕高度
        hideBtn: true//显示或者隐藏
      }
    },
    mounted() {
      this.date = formatDate(new Date(), "yyyy-MM-dd");
      this.id = this.$route.query.id;
      this.name = this.$route.query.name;
      let base64 = require('js-base64').Base64;
      this.userSign = base64.decode(sessionStorage.getItem("user_sign"));
      this.queryPostList();
      window.onresize = () => {
        return (() => {
          this.showHeight = document.body.clientHeight;
        })()
      };
    },
    methods: {
      queryPostList() {//查询理想岗位及曾任职工作
        this.axios.get(baseUrl + "/mechanismcomment/get_mechanism_type_list?mechanismId=" + this.id + "&sgin=" + this.userSign).then((res) => {
          let resultObj = res.data;
          if (resultObj.code == 0) {
            this.postList.push(resultObj.data);
            // for (let i = 0, length = resultObj.data.length; i < length; i++) {
            //   let name = resultObj.data[i].mechanismTypeName;//厂名
            //   let value = String(resultObj.data[i].id);
            //   let obj1 = {
            //     name: name,
            //     value: value
            //   };
            //   this.postList.push(obj1);
            //   let list = resultObj.data[i].workTypeList;
            //   for (let k = 0, length = list.length; k < length; k++) {
            //     let key = list[k].workTypeName;
            //     let parent = String(list[k].mechanismTypeId);
            //     let obj2 = {
            //       name: key,
            //       value: key,
            //       parent: parent
            //     };
            //     this.postList.push(obj2);
            //   }
            // }
          } else {
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch((error) => {
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      // onHide(type) {
      //   if (type) {
      //     this.post = [];
      //     this.post.push(this.$refs.postPicker && this.$refs.postPicker.getNameValues().split(" ")[1]);
      //   }
      // },
      inputBlur() {
        window.scrollTo(0, 0);
      },
      check() {
        if (this.post.length == 0) {
          this.$vux.toast.text("请选择理想岗位", "middle");
          return;
        } else if (this.month == "" || this.month == undefined) {
          this.$vux.toast.text("请选择薪资月份", "middle");
          return;
        }
        return true;
      },
      checkMoney(value) {//校验金额
        let money = value.trim();
        var reg = /^([1-9]\d{0,9}|0)([.]?|(\.\d{1,2})?)$/;
        if (money == "" || money == null) {
          this.$vux.toast.text("请输入正确的金额", "middle");
          return;
        } else if (money == 0 || !reg.test(money)) {
          this.$vux.toast.text("请输入正确的金额", "middle");
          return;
        }
        return true;
      },
      payRoll() {//提交
        let virtualMoney = this.money1;
        let ideaMoney = this.money2;
        if (this.check() && this.checkMoney(virtualMoney) && this.checkMoney(ideaMoney)) {
          this.$vux.loading.show({
            text: '加载中',
          });

          let data = {
            "idealMoney": virtualMoney,//理想薪资
            "mechanismId": this.id,//企业ID
            "payrollUrl": this.payroll,//工资单
            "post": this.post.toString(),//岗位
            "realMoney": ideaMoney,//实际工资
            "salaryMonth": this.month//月份
          };

          this.axios.post(baseUrl + "/mechanismcomment/add_salary?sgin=" + this.userSign, data).then((res) => {
            let resultObj = res.data;
            this.$vux.loading.hide();
            if (resultObj.code == 0 && resultObj.data != 0) {
              this.$vux.toast.text("提交成功,等待系统审核", "middle");
              setTimeout(() => {
                this.$router.push({path: "/mechanism", query: {"id": this.id, "name": this.name}});
              }, 50);
            } else {
              this.$vux.toast.text(resultObj.msg, "middle");
              return;
            }
          }).catch(() => {
            this.$vux.loading.hide();
            this.$vux.toast.text("网络异常", "middle");
          });
        }
      },
      changeImage(e) {//上传图片到七牛云
        if (e.target.files.length > 0) {
          getBase64(e.target, (url) => {
            this.payroll = 'data:image/png;base64,' + url;//显示图片

            //获取uploadToken
            this.axios.get(baseUrl + "/platform/get_token?sgin=" + this.userSign).then((res) => {
              let resultObj = res.data;
              let file = convertBase64ToBlob(this.payroll); //Blob 对象，上传的文件
              let key = null; // 上传后文件资源名以设置的 key 为主，如果 key 为 null 或者 undefined，则文件资源名会以 hash 值作为资源名。
              let config = {
                useCdnDomain: true, //表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
                region: qiniu.region.z2 // 根据具体提示修改上传地区,当为 null 或 undefined 时，自动分析上传域名区域};
              };

              let putExtra = {
                fname: "", //文件原文件名
                params: {}, //用来放置自定义变量
                mimeType: null //用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
              };
              let observable = qiniu.upload(file, key, resultObj.data, putExtra, config);

              observable.subscribe({
                next: (res) => {//主要用来展示进度
                  let total = res.total;
                },
                error: (err) => {//失败报错信息
                  this.$vux.toast.text("工资单上传失败，请重试", "middle");
                },
                complete: (res) => {//接收成功后返回的信息
                  this.payroll = "http://pic.lanpin123.com/" + res.hash;
                }
              })
            })
          })
        }
      },
      selectMonth(value) {//处理月份
        this.month = `${value.substr(0, 4)}年${value.substr(5, 2)}月`;
      }
    },
    watch: {
      showHeight() {
        if (this.docmHeight > this.showHeight) {
          this.hideBtn = false;
        } else {
          this.hideBtn = true;
        }
      }
    },
    components: {
      PopupPicker,
      Picker,
      Datetime
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../common/stylus/mixin.styl"

  .payroll-wrap
    margin: 0 auto
    wh(100%, 100%)
    overflow: hidden
    .payroll-box
      display: flex
      align-items: center
      wh(100%, 1.28rem)
      size-color(0.427rem, rgba(51, 51, 51, 1))
      border-bottom: 0.027rem solid #f2f2f2
      .title
        margin-left: 0.32rem
      .name
        display: flex
        align-items: center
        margin-left: auto
        margin-right: 0.32rem
        color: rgba(27, 27, 27, 1)
        .money
          text-align: right
          height: 0.5rem
          line-height: 0.5rem
          size-color(0.44rem, rgba(27, 27, 27, 1))
      .name >>> .vux-tap-active
        width: 100%
        padding: 0 0
      .name >>> .weui-cell__ft
        text-align: right
      .name >>> .weui-cell__ft .vux-cell-placeholder
        color: #cccccc
      .name >>> .vux-cell-primary .vux-popup-picker-select
        text-align: right !important
      .name >>> .vux-cell-primary .vux-popup-picker-placeholder
        color: #cccccc
      .work
        flex: 1
        margin-right: 0.187rem
      .back-box
        margin-left: auto
        margin-right: 0.32rem
        .back
          wh(0.32rem, 0.32rem)
    .pic-box
      display: flex
      margin-top: 0.427rem
      .pic-title
        font-size: 0.427rem
        color: rgba(51, 51, 51, 1)
        margin-left: 0.32rem
      .pay-picture
        position: relative
        margin-left: auto
        margin-right: 0.32rem
        wh(3.027rem, 3.027rem)
        margin-top: 0.28rem
        z-index: 1
        .pay-box
          wh(3.027rem, 3.027rem)
          fj(center, center)
          .roll-box
            wh(3.027rem, 3.027rem)
            .roll
              wh(100%, 100%)
    .photo
      position: absolute
      top: 0
      opacity: 0
      -ms-filter: 'alpha(opacity=0)'
      z-index: 999
      wh(100%, 3.027rem)
    .payroll
      wh(100%, 3.027rem)
      border-radius: 0.213rem
    .btn
      position: fixed
      bottom: 0.48rem
      left: 0
      right: 0
      margin: auto
      fj(center, center)
      wh(93.6%, 1.333rem)
      background: rgba(60, 175, 255, 1)
      border: 0.013rem solid rgba(238, 238, 238, 1)
      border-radius(0.133rem)
      size-color(0.48rem, rgba(254, 255, 255, 1))
</style>
